<template>
    <div>
        <index-header></index-header>

        <el-container class="box">

            <div style="width:1000px;height:auto;">
                <div class="items-head">
                    <span class="cart-title">购物车（全部{{ total }}）</span>
                    <div class="items-right">
                        <span class="cart-title-1">已选商品（不含运费）</span>
                        <span class="cart-title-2">￥{{ totalprice }}</span>
                        <el-button class="cart-title-btn" type="danger" @click="purchaseBuy" round>添加订单</el-button>
                    </div>

                </div>

                <div style="width:999px;height:auto;padding-bottom:20px;color:#FFFFF;margin-top: 36px;">

                    <table>
                        <thead v-if="cartList.length > 0">
                            <tr>
                                <td width="80px">
                                    <el-checkbox v-model="checkAll" @click="goCheckAll" label="全选" size="large" />
                                </td>
                                <td style="width:350px;text-align:left;padding-left: 15px;">商品</td>
                                <td>单价</td>
                                <td style="width:120px;">数量</td>
                                <td style="width:120px;">金额</td>
                                <td style="width:120px;">操作</td>
                            </tr>
                        </thead>

                        <tbody ref="tbody">
                            <tr v-for="(item, index) in cartList" :key="index"
                                style="margin-top:10px;padding-bottom:10px;">

                                <el-checkbox @click="goCheck(item)" v-model="item.checked" size="large" />
                                <td width="350px;" @click="cartDetail(item)">
                                    <div class="content">
                                        <div class="imgbox">
                                            <img :src="item.bookpic" alt="图片走丢了">
                                        </div>
                                        <p class="p-name">{{ item.bookname }}</p>
                                        <p class="p-name" style="color:gray">类别：{{ item.typename }}</p>

                                    </div>
                                </td>
                                <td style=" color: #FF4400;">{{ item.price }}</td>
                                <td><el-input-number v-model="item.cartNum" :min="1" size="small" :max="10"
                                        @change="handleChange(item)" />
                                </td>
                                <td style=" color: #FF4400;font-size: 20px">￥{{ item.price * item.cartNum }}</td>
                                <td>
                                    <el-tag class="mx-1" @click="deleteBook(item)" type="danger"
                                        size="small">删除</el-tag>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    <el-empty description="您的购物车空空也~~" v-if="cartList.length == 0" />
                </div>
            </div>
        </el-container>

        <div class="fixed" ref="drag">
            <div>
                <el-checkbox v-model="checkAll" @click="goCheckAll" label="全选" size="large" />
            </div>
            <div>
                <el-tag class="mx-1" @click="deleteList" type="danger" size="large">删除选中</el-tag>
            </div>
            <div>已选商品{{ totalnum }}</div>
            <div>
                合计 <span style="bcakground:red; width:60px;height:60px;color: orangered;font-size: 20px">
                    ￥{{ totalprice }}
                </span>
            </div>
            <div>
                <el-button type="danger" @click="purchaseBuy" round>添加订单</el-button>
            </div>
        </div>

        <!-- 结算清单 -->
        <el-dialog v-model="centerDialogVisible" title="确认订单" width="50%" center>
            <div>
                <h4>已选商品:{{ totalnum }}件</h4>
                <h4>总合计价格:{{ totalprice }}元</h4>
            </div>

            <el-table :data="payList" style="margin-bottom:30px;">

                <el-table-column property="bookname" label="商品名" />
                <el-table-column property="price" label="价格/元" />
                <el-table-column property="cartNum" label="数量/本" />
                <el-table-column property="" label="小计/元">
                    <template #default="scope">
                        {{ scope.row.price * scope.row.cartNum }}元
                    </template>
                </el-table-column>
            </el-table>
            <div>
                <label>地址：</label>
                <el-select v-model="addressId" :data="addressList" placeholder="请选择收货地址" style="width:400px;">
                    <el-option v-for="item in addressList" @click="AddresssubmitId(item.addressId)"
                        :key="item.addressId"
                        :label="item.provinces + '/' + item.city + '/' + item.county + '/' + item.detailAddress"
                        :value="item.addressId">
                    </el-option>
                </el-select>
                <br /> <br />
                <label>支付方式:</label>
                <el-select v-model="paytype" :data="payTypeList" placeholder="请选择支付方式" style="width:200px;">
                    <el-option v-for="item in payTypeList" @click="setpayType(item.name)" :key="item.value"
                        :label="item.name" :value="item.name">
                    </el-option>
                </el-select>

            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitPayList" >
                        <!-- @click="submitPayList" -->
                        提交订单
                    </el-button>
                </span>
            </template>
        </el-dialog>

    </div>
</template>
    
<script>
import { reactive, toRefs, computed, ref } from "vue";
import { useRouter } from "vue-router"
import { getUserCartApi, updateCartApi, deleteCartApi, deleteCartListApi, AddressApi, addOrderApi } from "../utils/clientApi"
import indexHeader from './indexHeader.vue'
import { ElMessage } from 'element-plus';
// import { del } from '@/utils/service';
export default {
    components: { indexHeader },
    name: "userCart",
    setup() {
        const router = useRouter()
        let data = reactive({
            cartList: [],
            //是否全选
            checkAll: false,
            //总合计价格
            totalprice: 0,
            //总数量
            totalnum: 0,
            total: 0,
            // 修改数量
            updateCartNum: {
                u_Id: '',
                b_Id: '',
                cartNum: ''
            },
            delList: [],
            payList: [],
            centerDialogVisible: false,
            // 地址ID
            addressId: "",
            addressList: [],
            // 支付方式
            paytype: "",
            paytime: "",
            payTypeList: [{ "name": "微信", value: 1 }, { "name": "支付宝", value: 2 }],
            user_Id: 0
        })

        // 获取用户购物车列表
        const getCartList = () => {
            data.user_Id = JSON.parse(localStorage.getItem("userInfo")).id;
            getUserCartApi(data.user_Id).then(res => {
                console.log(res);
                if (res.status === 200) {
                    data.cartList = res.data
                } else if (res.status === 201) {
                    ElMessage.error(res.msg)
                } else if (res.status === 202) {
                    ElMessage.error(res.msg)
                }
            })
        }
        getCartList()

        // 修改数量
        const handleChange = (item) => {
            data.updateCartNum.u_Id = JSON.parse(localStorage.getItem("userInfo")).id;
            data.updateCartNum.b_Id = item.bookId
            data.updateCartNum.cartNum = item.cartNum

            updateCartApi(JSON.stringify(data.updateCartNum)).then(res => {
                if (res.status === 202) {
                    ElMessage.error(res.msg)
                }
            })
        }
        // 删除一条记录
        const deleteBook = (item) => {
            const u_Id = JSON.parse(localStorage.getItem("userInfo")).id;
            const bookId = item.bookId
            const del = { u_Id: u_Id, b_Id: bookId }
            deleteCartApi(del).then(res => {
                if (res.status === 200) {
                    ElMessage.success(res.msg)

                }
                getCartList()
            })
        }
        // 批量删除
        const deleteList = () => {
            let list = []
            data.cartList.forEach((item) => {
                if (item.checked) {
                    list.push(item.cartId)
                }
            })
            if (list.length !== 0) {
                deleteCartListApi(JSON.stringify(list)).then(res => {
                    if (res.status === 200) {
                        ElMessage.success(res.msg)
                        window.location.reload()
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            } else {
                ElMessage.error("请勾选选项")
            }
        }


        function goCheckAll() {
            //数值是点击之前的值 所以要取反
            if (!data.checkAll) {
                data.cartList.forEach((item) => {
                    item.checked = true
                })
            } else {
                data.cartList.forEach((item) => {
                    item.checked = false
                })
            }
        }

        function goCheck(item) {
            //数值是点击之前的值 所以要取反
            //定义一个长度
            let length = 1
            data.cartList.forEach((i) => {
                if (i.checked) {
                    length++
                }
            })
            if (length === data.cartList.length) {
                data.checkAll = true
            } else {
                data.checkAll = false
            }
        }


        //计算被选中的商品的总价格
        data.totalprice = computed(() => {
            let totalprice = 0
            data.cartList.forEach((item) => {
                if (item.checked) {
                    totalprice += parseInt(item.price) * item.cartNum
                }
            })
            return totalprice
        });
        //      计算被选中的商品数量
        data.totalnum = computed(() => {
            let totalnum = 0;

            data.cartList.forEach((item) => {
                if (item.checked) {
                    totalnum++;
                }
            });

            return totalnum
        });

        //      计算购物车的商品数量
        data.total = computed(() => {
            let total = 0
            if (data.cartList.length !== 0) {
                data.cartList.forEach(() => {
                    total++
                })
            }
            return total
        });

        const drag = ref(null)
        // 查看详情
        const cartDetail = (item) => {
            router.push({
                path: '/goodsdetail',
                query: {
                    bookId: item.bookId
                }
            })
        }
        // 获取用户地址列表
        const getAddressList = () => {
            const id = JSON.parse(localStorage.getItem("userInfo")).id
            AddressApi(id).then(res => {
                data.addressList = res.data
                data.addressList.forEach((item) => {
                    if (item.isDefault == 1) {
                        // 赋值默认地址
                        data.addressId = item.addressId

                    }
                })
            })
        }


        //  // 支付
        //  const pay = () => {
        //    const userId = JSON.parse(localStorage.getItem("userInfo")).id;
        //     window.open("http://43.142.131.251:8081/alipay/pay?subject=" + 'user-'+userId+'buy' + "&totalAmount=" + totalprice + "&traceNo=" + orders.orderFId)
        // }

        // 结算
        const purchaseBuy = () => {
            // 判断是否被选择
            let list = []
            data.cartList.forEach((item) => {
                if (item.checked) {
                    list.push(item)
                }
            })
            // 判断选中的记录是否为0
            if (list.length > 0) {
                data.payList = list
                data.centerDialogVisible = true
                getAddressList()
                console.log(data.addressId);
            } else {
                ElMessage.error("您还没选中宝贝呢~~")
            }
        }

        // 选择支付方式
        const setpayType = (value) => {
            data.paytype = value
            data.paytime = Date.parse(new Date());
        }
        const AddresssubmitId = (id) => {
            // 修改地址id
            data.addressId = id
            // console.log("我是修改后的地址ID",data.addressId);
        }


        // 处理map转json为空
        const strMapToObj = (strMap) => {
            let obj = Object.create(null);
            for (let [k, v] of strMap) {
                obj[k] = v;
            }
            return obj;
        }

        // 提交
        const submitPayList = () => {
            // 提交的内容
            // 商品id
            // let order={goodslist:"",addressId:'',paytype:''}

            if (data.paytype.length !== 0) {
                let map = new Map();
                const id = JSON.parse(localStorage.getItem("userInfo")).id
                let list = []
                let map2 = new Map();
                data.payList.forEach((item) => {
                    map2.set("cartId", item.cartId)
                    map2.set("goodId", item.bookId)
                    map2.set("price", item.price)
                    map2.set("countNum", item.cartNum)
                    let obj = strMapToObj(map2)
                    list.push(obj)
                })
                map.set("goodList", list)
                map.set("addressId", data.addressId)
                map.set("paytype", data.paytype)
                map.set("uid", id)
                map.set("amountMoney", data.totalprice)
              

                addOrderApi(JSON.stringify(strMapToObj(map))).then(res => {
                    if (res.status === 200) {
                        ElMessage.success(res.msg)
                        data.centerDialogVisible = false
                        router.push({
                            path:'/order'
                        })
                    } else if (res.status === 201) {
                        ElMessage.error(res.msg)
                    }

                })
            } else {
                ElMessage.error("请选择支付方式")
            }
        }

        return {
            ...toRefs(data),
            getCartList, goCheckAll, goCheck, drag, cartDetail, AddresssubmitId,
            handleChange, deleteBook, deleteList, purchaseBuy, submitPayList, setpayType, strMapToObj
        }
    }
}
</script>
    
<style>
.box {
    border-radius: 30px 30px 0 0;
    width: 1000px;
    height: auto;
    margin: 0 auto;
    margin-top: 20px;
    background: rgb(255, 255, 255);
    margin-bottom: 110px;
}

.items-head {

    width: 1000px;
    height: 20px;
    background: #FFFF;
    border-radius: 30px 30px 0 0;
}

.cart-items {
    display: flex;
    width: 1000px;
    height: 160px;
    margin: 0 auto;
    background: red;
    margin-bottom: 13px;
}

.fixed {
    position: fixed;
    top: 90%;
    left: 50%;
    transform: translate(-50%, -50%);

    margin: 0 auto;
    width: 1100px;
    height: 70px;
    background: #FFFF;
    text-align: center;
    line-height: 101px;
    display: flex;
    align-items: center;
    border-radius: 10px 10px 10px 10px;
    justify-content: space-around;
    background: #FFFFFF;
}


.cart-title {
    font-size: 18px;
    font-weight: 20px;
    position: relative;
    top: 20px;
    left: -225px;
}

.items-right {
    width: 350px;
    height: 60px;
    float: right;

}

.cart-title-1 {
    position: relative;
    left: -27px;
    top: 20px;
}

.cart-title-2 {
    position: relative;
    left: -16px;
    top: 20px;
    font-size: 19px;
    color: #FF4400;
}

.cart-title-btn {
    position: relative;
    left: 20px;
    top: 18px;
}

/*列表*/
.shoppingTrolley .content {
    width: 1000px;
    margin: 0 auto;
    min-height: 700px;
    box-sizing: border-box;
}

table {
    width: 100%;
}

tbody .imgbox {
    margin-left: 10px;
    width: 90px;
    height: 100px;
    overflow: hidden;
    float: left;
}

tbody .imgbox img {
    height: 100px;
    width: 100%;
}

.content {

    width: 350px;
    height: 100px;
}

.p-name {
    display: block;
    position: relative;
    top: 12px;
    left: 22px;
    font-size: 14px;
    text-align: left;
}

.mx-1:hover {
    cursor: pointer;
}
</style>